/*
 * @Author: huangyingli
 * @Date: 2023-02-07 19:07:49
 * @LastEditors: huangyingli
 * @LastEditTime: 2023-02-22 18:54:13
 * @Description: 
 */
// eslint-disable-next-line no-unused-vars
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

import { STATUS } from '../config';

import { isLoginRequest } from '../api/auth';

const initialState = {
  userId: '',
  status: STATUS.IDLE,
  loading: false,
  isLogin: undefined,
};

export const fetchIsLogin = createAsyncThunk(
  'common/fetchIsLogin',
  async () => {
    const response = await isLoginRequest();
    return response.data;
  }
);

const commonSlice = createSlice({
  name: 'common',
  initialState,
  reducers: {
    setUserId(state, action) {
      const id = action.payload;
      state.userId = id;
      state.isLogin = true;
    },
    setStatus(state, action) {
      state.status = action.payload;
      if (state.status === STATUS.LOADING) {
        state.loading = true;
      } else {
        state.loading = false;
      }
    },
    loginout(state, action) {
      state.isLogin = false;
      state.userId = '';
    },
  },
  extraReducers(builder) {
    builder.addCase(fetchIsLogin.fulfilled, (state, action) => {
      state.isLogin = action.payload.data || false;
    });
  },
});

export const { setUserId, setStatus, loginout } = commonSlice.actions;

export default commonSlice.reducer;

export const getUserId = (state) => state.common.userId;

export const getStatus = (state) => state.common.status;

export const getLoading = (state) => state.common.loading;

export const getIsLogin = (state) => state.common.isLogin;
